package it.rap.application.logic.mappers;

import it.rap.application.logic.BusinnessLogic;
import it.rap.applications.persistence.entities.filters.FilterTree;
import it.rap.applications.persistence.entities.filters.RoleTree;

import java.math.BigDecimal;
import java.util.List;

import javax.persistence.Query;

public class FiltersLogicNew extends BusinnessLogic {

	private StringBuffer selectAllQuery = new StringBuffer().append(" SELECT f FROM FilterTree f ORDER BY f.id DESC "); 
	
	public FiltersLogicNew() {
		super("publisher");
	}
	
	public FilterTree find(BigDecimal id){
		return enm.find(FilterTree.class, id );
	}
	
	public void persist(FilterTree f) {
		List<RoleTree> rList = f.getRoleTreeList();
		if( rList != null && rList.size() > 0 ){
			for ( RoleTree r: rList ){
				enm.persist( r );
			}
		}
		enm.persist( f );
	}

	public void persist(RoleTree r) {
		List<RoleTree> subRoleList = r.getSubRoleTreeList();
		if ( subRoleList != null && subRoleList.size() > 0 ){
			for( RoleTree sr: subRoleList ){
				enm.persist( sr );
			}
		}
		enm.persist( r );
		if ( r.getFilterTree() != null ){
			enm.merge( r.getFilterTree() );
		}
		if ( r.getSubRoleTree() != null ){
			enm.persist( r.getSubRoleTree() );
		}
	}
	
	public List<FilterTree> selectAll(Integer currentDataOffset, Integer currentDataLimit) {
		Query query = enm.createQuery( selectAllQuery.toString() ).setFirstResult( currentDataOffset ).setMaxResults( currentDataLimit );	
		List<FilterTree> fList = (List<FilterTree>)query.getResultList();
		return fList;
	}

	public List<FilterTree> selectAll() {
		Query query = enm.createQuery( selectAllQuery.toString() );	
		List<FilterTree> fList = (List<FilterTree>)query.getResultList();
		return fList;
	}

	public void remove(RoleTree role) {
		if ( role.getFilterTree() != null ){
			role.getFilterTree().getRoleTreeList().remove( role );
		}
		if ( role.getSubRoleTree() != null ){
			role.getSubRoleTree().getSubRoleTreeList().remove( role );
		}
		enm.remove( role );
	}

	public void refresh(FilterTree f) {
		enm.refresh( f );
	}
	
	public void refresh(RoleTree r) {
		enm.refresh( r );
		enm.refresh( r.getFilterTree() );
	}
	
	public void merge( FilterTree f ){
		enm.merge( f );
	}
	
	public void merge( RoleTree r ){
		enm.merge( r );
		enm.merge( r.getFilterTree() );
	}

	public void remove(FilterTree f) {
		enm.remove( f );
	}
	

}
